package com.example.serviceability;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.rpc.*;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.zson.ZSONObject;

import java.util.HashMap;
import java.util.Map;

public class ComputeService extends Ability {

    // 创建用于计算数据的远程对象
    class MyRemoteObject extends RemoteObject implements IRemoteBroker {

        MyRemoteObject() {
            super("MyRemoteObject");
        }

        @Override
        public boolean onRemoteRequest(int code, MessageParcel data, MessageParcel reply, MessageOption option) {
            // 判断调用代码
            if (code != 1001) {
                reply.writeString("调用错误!");
                return false;
            }

            // 获取输入参数这里最好用try-catch捕获异常
            ZSONObject object = ZSONObject.stringToZSON(data.readString());
            int a = object.getInteger("variableA");
            int b = object.getInteger("variableB");
            // 计算输出结果
            int result = a * b;
            // 将输出结果进行包装
            ZSONObject resultObject = new ZSONObject();
            resultObject.put("code", 200);
            resultObject.put("result", result);
            String output = ZSONObject.toZSONString(resultObject);
            // 返回输出结果
            reply.writeString(output);

            return true;
        }

        @Override
        public IRemoteObject asObject() {
            // 返回当前对象
            return this;
        }
    }

    @Override
    public IRemoteObject onConnect(Intent intent) {
        // 返回远程代理对象
        return new MyRemoteObject().asObject();
    }
}